package com.cuit.dashboard.system.controller;


import com.cuit.dashboard.common.util.Result;
import com.cuit.dashboard.system.entity.SysAdminEntity;
import com.cuit.dashboard.system.entity.vo.LoginVO;
import com.cuit.dashboard.system.oauth2.Oauth2Token;
import com.cuit.dashboard.system.service.SysAdminService;
import com.cuit.dashboard.system.service.SysAdminTokenService;
import com.cuit.dashboard.system.service.SysLoginLogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @program: zuke
 * @description: 登录
 * @author: KamTang
 * @create: 2022-06-11 19:29
 **/
@RestController
@RequestMapping("/sys")
public class SysLoginController extends SysAdminAbstractController {

    @Autowired
    private SysAdminService adminService;

    @Autowired
    private SysAdminTokenService sysAdminTokenService;

    @Autowired
    private SysLoginLogService loginLogService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginVO loginVO, HttpServletRequest request) throws UnsupportedEncodingException {
        // 用户信息
        SysAdminEntity admin = adminService.queryByUserName(loginVO.getUsername());

        // 账号不存在、密码错误
        if (admin == null || !admin.getPassword().equals(new Sha256Hash(loginVO.getPassword(), admin.getSalt()).toHex())) {
            return Result.error("账号或密码不正确");
        }

        // 账号锁定
        if (admin.getStatus() == 0) {
            return Result.error("该账号已被锁定,请联系管理员");
        }
        Result result = sysAdminTokenService.createToken(admin.getUserId());
        String token = (String) result.get("token");
        Oauth2Token oauth2Token = new Oauth2Token(token);
        SecurityUtils.getSubject().login(oauth2Token);
        //生成token，并保存到数据库
        //loginLogService.addLoginReport(request);
        return result;
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/logout")
    public Result logout() {
        sysAdminTokenService.logout(getAdmin().getUserId());
        return Result.ok();
    }
}
